package cn.felord.security.autoconfigure.miniapp;

import cn.felord.security.autoconfigure.AbstractLoginChannelProcessor;
import cn.felord.security.autoconfigure.ChannelUserDetailsService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.AuthenticationProvider;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * @author n1
 * @since 2021/6/29 9:45
 */
public class MiniAppLoginChannelProcessor extends AbstractLoginChannelProcessor<MiniAppAuthenticationToken> {
    private static final String CHANNEL_ID = "miniapp";
    private final ObjectMapper om = new ObjectMapper();


    public MiniAppLoginChannelProcessor(ChannelUserDetailsService channelUserDetailsService) {
        super(CHANNEL_ID, new MiniAppAuthenticationProvider(channelUserDetailsService));
    }

    public MiniAppLoginChannelProcessor(String channel, AuthenticationProvider appAuthenticationProvider) {
        super(channel, appAuthenticationProvider);
    }

    @Override
    public MiniAppAuthenticationToken doAuthenticationRequest(HttpServletRequest request) throws IOException {
        BufferedReader reader = request.getReader();
        MiniAppRequest miniAppRequest = om.readValue(reader, MiniAppRequest.class);
        return new MiniAppAuthenticationToken(miniAppRequest);
    }
}
